package com.cloud.bc.controller.ajax;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.bc.config.AliOssConfig;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.BcCategoryGroups;
import com.cloud.bc.model.entity.BcCategorys;
import com.cloud.bc.model.entity.BcSingles;
import com.cloud.bc.model.entity.BcUserPhotos;
import com.cloud.bc.model.enums.RedisKey;
import com.cloud.bc.model.response.AjaxResp;
import com.cloud.bc.service.*;
import com.cloud.bc.util.BcUtils;
import com.cloud.common.oss.AliOssRequest;
import com.cloud.common.oss.AliOssResponse;
import com.cloud.common.oss.AliUploadHelper;
import com.cloud.common.util.EmailUtil;
import com.cloud.common.util.SmsUtil;
import com.cloud.redis.config.RedisUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@AllArgsConstructor
@RestController
@RequestMapping("m/ajax/common")
public class Ajax_CommonController {
    private final BcCategorysService bcCategorysService;
    private final BcCategoryGroupsService bcCategoryGroupsService;

    private final RedisUtils redisUtils;
    private final SmsUtil smsUtil;
    private final EmailUtil mailUtil;
    private final AliOssConfig aliOssConfig;
    private final BcUserPhotosService bcUserPhotosService;
    private final BcUsersService bcUsersService;
    private final BcSinglesService bcSinglesService;
    private final BcUtils bcUtils;

//    @GetMapping("category")
//    public String sendsmscode() {
//        String key = RedisKey.bcCategoryRedisKey;
//        Object o = redisUtils.get(key);
//        if (null != o && !Convert.toStr(o).equals("")) {
//            //写数据
//            return Convert.toStr(o);
//        }
//        StringBuilder sb = new StringBuilder();
//        sb.append("var BOTTLECMS_category = [];");
//        List<BcCategoryGroups> bcCategoryGroups = bcCategoryGroupsService.selectAll(null);
//        List<BcCategorys> bcCategorys = bcCategorysService.selectAll(null);
//
//        for (BcCategoryGroups group :
//                bcCategoryGroups) {
//            String alias = group.getAlias();
//            sb.append("BOTTLECMS_category." + alias + "= [");
//            List<String> arr = new ArrayList<>();
//            List<BcCategorys> categorysList = bcCategorys.stream().filter(t -> t.getAlias().equals(alias)).collect(Collectors.toList());
//            for (BcCategorys item : categorysList) {
//                arr.add("\"" + item.getId() + ":" + item.getName() + "\"");
//            }
//            sb.append(StrUtil.join(",", arr));
//            sb.append("];");
//        }
//        String string = sb.toString();
//        redisUtils.set(key, string);
//        return string;
//    }

    /**
     * 上传
     */
    @PostMapping("upload")
    public AjaxResp upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        if (null == userInfo) {
            return ajaxResp;
        }
        String filedir = request.getParameter("filedir");
        //落库时图片类型
        String typeName = request.getParameter("previews");
        if (StrUtil.isEmpty(typeName)) {
            //如果是空的默认就是相册
            typeName = "album";
        } else {
            typeName = StrUtil.replace(typeName, ".", "");
        }
        String origionalName = multipartFile.getOriginalFilename();
        String staff = "jpg";
        if (!StrUtil.isEmpty(origionalName)) {
            staff = StrUtil.subAfter(origionalName, ".", true);
//            String[] split = origionalName.split(".");
        }
//        String filePath = filedir + "/" + DateUtil.today().replace("-", "/") + "/" + UUID.randomUUID().toString() + "." + staff;
        String filePath = bcUtils.createOssFiledir(filedir, staff);
        FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
        AliOssRequest aliOssRequest = new AliOssRequest();
        BeanUtil.copyProperties(aliOssConfig, aliOssRequest);
        AliUploadHelper aliUploadHelper = new AliUploadHelper(aliOssRequest);
        AliOssResponse aliOssResponse =
                aliUploadHelper.uploadSimple(inputStream, filePath);
        ajaxResp.setObj(aliOssResponse.getAbsolutePath());
        ajaxResp.setMsg("上传成功");
        if (filedir.equals("album")) {
            //只有相册数据才会落库
            BcUserPhotos bcUserPhotos = new BcUserPhotos();
            bcUserPhotos.setUserId(userInfo.getId());
            bcUserPhotos.setPhoto(aliOssResponse.getAbsolutePath());
            bcUserPhotos.setTitle(typeName);
            bcUserPhotosService.setPhotoData(bcUserPhotos);
        }
        return ajaxResp;
    }

    /**
     * 上传blob方式
     */
    @PostMapping("upload_blob")
    public AjaxResp upload_blob(HttpServletRequest request) throws IOException {
        String base64file = request.getParameter("base64file");
//        List<String> allGroup1 = ReUtil.findAllGroup1("data:(.*?);base64,", base64file);
//        String imgType = allGroup1.stream().findFirst().orElse("");
        String fileData = "";
        String[] splitFile = StrUtil.split(base64file, ",");
        if (splitFile.length > 1) {
            fileData = splitFile[1];
        }
        BufferedImage bufferedImage = ImgUtil.toImage(fileData);
        InputStream inputStream = bufferedImageToInputStream(bufferedImage);
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        String typeName = request.getParameter("filedir");
        String filedir = bcUtils.createOssFiledir(typeName, "jpg");
        AliOssRequest aliOssRequest = new AliOssRequest();
        BeanUtil.copyProperties(aliOssConfig, aliOssRequest);
        AliUploadHelper aliUploadHelper = new AliUploadHelper(aliOssRequest);
        AliOssResponse aliOssResponse =
                aliUploadHelper.uploadSimple(inputStream, filedir);
        AjaxResp ajaxResp = new AjaxResp();
        ajaxResp.setObj(aliOssResponse.getAbsolutePath());
        ajaxResp.setMsg("上传成功");
        setSinglesHeadPhoto(userInfo, aliOssResponse.getAbsolutePath());
        return ajaxResp;
    }

    /**
     * 设置头象
     */
    private void setSinglesHeadPhoto(UserInfo userInfo, String photoPath) {
        BcSingles bcSingles = new BcSingles();
        bcSingles.setPhoto(photoPath);
        bcSingles.setPhotoAt(new Date());
        //把头象改为待审核
        bcSingles.setPhotoCheck(3);
        bcSingles.setIsAuth(1);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userInfo.getId());
        bcSinglesService.update(bcSingles, queryWrapper);
    }

    /**
     * 将BufferedImage转换为InputStream
     *
     * @param image
     * @return
     */
    public InputStream bufferedImageToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
        }
        return null;
    }
}
